﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace SF.Utilities
{
    public static class RegexHelper
    {
        private static readonly string ruleRemoveHtmlTag = @"[<].*?[>]";

        /// <summary>
        /// 从<see cref="source"/>中移除HTML标签后返回新的字符串
        /// </summary>
        /// <param name="source">目标字符串</param>
        /// <returns></returns>
        public static string RemoveHtmlTag(this string source)
        {
            return Regex.Replace(source, ruleRemoveHtmlTag, "");
        }

        /// <summary>
        /// 从<see cref="commandText"/>中根据<see cref="token"/>分离出参数并以数组形式返回
        /// </summary>
        /// <param name="commandText">目标命令字符串</param>
        /// <param name="token">参数标记符号，默认为 @</param>
        /// <returns></returns>
        public static string[] GetParameters(string commandText, string token = "@")
        {
            List<string> list = new List<string>();
            if (string.IsNullOrWhiteSpace(commandText))
            {
                return list.ToArray();
            }
            foreach (string line in commandText.Split('\n', '\r'))
            {
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }
                for (int i = 0; i < line.Length; i++)
                {
                    var c = line[i];
                    if (c.ToString() == token)
                    {
                        StringBuilder builder = new StringBuilder();
                        while (i != line.Length - 1 && line[++i].IsNormal())
                        {
                            builder.Append(line[i]);
                        }
                        var name = builder.ToString();
                        if (name.Length > 0) { list.Add(name); }
                    }
                }
            }
            return list.Distinct(StringComparer.CurrentCultureIgnoreCase).ToArray();
        }
    }
}
